﻿/*******************************************************************************
 * Copyright (c) 2011 Technische Universität Darmstadt
 * 					  Fachbereich Informatik
 * 					  Theoretische Informatik - Kryptographie und Computeralgebra
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

var info = Components.classes["@mozilla.org/xre/app-info;1"]
.getService(Components.interfaces.nsIXULAppInfo);

if(info.version.charAt(0)<5){
	Components.utils.import("resource://app/modules/errUtils.js"); // not comp w TB5
	Components.utils.import("resource://app/modules/gloda/utils.js"); //not tb5
	Components.utils.import("resource://app/modules/gloda/gloda.js"); //not tb5
}
Components.utils.import("resource://gre/modules/iteratorUtils.jsm");
Components.utils.import("resource:///modules/MailUtils.js");
Components.utils.import("resource:///modules/gloda/mimemsg.js");
Components.utils.import("resource:///modules/gloda/noun_mimetype.js");

if(info.version.charAt(0)>=5){
	Components.utils.import("resource://gre/modules/AddonManager.jsm"); //needed!
	Components.utils.import("resource://gre/modules/Services.jsm");
}

/*============================================================================*/
/* SUBJECT ENCRYPTION
/*============================================================================*/
var stringBundlef;

window.addEventListener("load", function(){
	stringBundlef = document.getElementById("cryptoBirdStringBundle");
}, false);


function onAboutCBMenuItemCommand(event){	
	var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
	prompts.alert(null, stringBundlef.getString("cryptoBird.compose.infowindowtitle"),stringBundlef.getString("cryptoBird.compose.info")); //getStringFromName
}

function onEncSubjectMenuItemCommand(event){
	if (subjectEncrypted)
		subjectEncrypted = false;
	else
		subjectEncrypted = true;
}

var subjectEncrypted = false;

var SendMessageOriginal = SendMessage;
var SendMessage = function() {
	encryptAndSend(); 
};

var SendMessageWithCheckOriginal = SendMessageWithCheck;
var SendMessageWithCheck = function () {
	encryptAndSend(); 
};

var SendMessageLaterOriginal = SendMessageLater;
var SendMessageLater = function () {
	encryptAndSend(); 
};

function encryptAndSend() {
	var win = Components.classes["@mozilla.org/appshell/window-mediator;1"].
	getService(Components.interfaces.nsIWindowMediator).
	getMostRecentWindow("mail:3pane");
	var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
	var fine = true;
	try {
		if (subjectEncrypted && !document.getElementById("msgSubject").value.length==0){
			var pubringPath;
			var pubringFile;
			if(info.version.charAt(0)<5){
				pubringPath = navigator.preference('cryptoBird.pgp_path');
				pubringFile = navigator.preference('cryptoBird.pgp_pk_name');
			}else{ //if preference is not found an exception is thrown
				try{
					pubringPath = Services.prefs.getCharPref('cryptoBird.pgp_path');
					pubringFile = Services.prefs.getCharPref('cryptoBird.pgp_pk_name');
				}catch(e){
				}
			}
			if(pubringPath == '' || pubringPath == '/'){
				prompts.alert(null, stringBundlef.getString("cryptoBird.compose.errorwindowtitle"), stringBundlef.getString("cryptoBird.compose.errorpgp"));
				//prompts.alert(null, "Error", "Please enter PGP key locations!");
				fine= false;
			}else{
				var userIDs = new Array();
				var i = 0;
				while (true){
					var recTmp = document.getElementById("addressCol2#"+(i+1));
					if (recTmp!=null){
						var recipient = recTmp.label;
						if (recipient!=null && recipient.length>0) {
							userIDs[i] = recipient;
							i = i+1;
						} else break;
					}
					else break;
				}

				var sender = document.getElementById("msgIdentity").description;

				if (!(userIDs==null) && userIDs.length>0){
					userIDs[i] = sender;
					var subject = win.TheChasingDragon.cryptoBirdJava.encryptSubject(userIDs, document.getElementById("msgSubject").value, pubringPath, pubringFile);
					if (subject.indexOf("--NO KEY--")>-1){
						//prompts.alert(null, "Error", 'Subject encryption not possible: Could not find any key for '+subject.substring(10)+'.');
						prompts.alert(null, stringBundlef.getString("cryptoBird.compose.errorwindowtitle"), stringBundlef.getString("cryptoBird.compose.errorkeys")+' '+subject.substring(10));
						fine = false;
					} else {
						document.getElementById("msgSubject").value = '-----SUBJECT ENCRYPTED-----'+subject;
						SendMessageOriginal.apply(this, arguments);
					}	
				} else{ 
					prompts.alert(null, stringBundlef.getString("cryptoBird.compose.errorwindowtitle"), stringBundlef.getString("cryptoBird.compose.errorrecipient"));
					//prompts.alert(null, "Error", "Please check your recipient!");

					fine = false;
				}		
			}
		} else SendMessageOriginal.apply(this, arguments);
	} catch (err) {
		fine = false;
		return;
	}
	//set to false again if message is sent
	if(fine){
		subjectEncrypted = false;
		document.getElementById('cryptobird-encSubject').removeAttribute("checked");
	}
}
